import React, { PureComponent } from 'react';
import { StyleSheet, Text, TouchableOpacity, View, Image, ImageBackground, Dimensions, Modal, TouchableWithoutFeedback } from 'react-native';
import { connect } from 'react-redux';
import { BrickButton, Divider, Slider, Popup } from 'tuya-panel-kit';
import TYSdk from '../../api';
import Strings from '../../i18n';
import SwitchButton from "../../components/SwitchButton";
import dpCodes from "../../config/dpCodes";
import { debounce } from "../../utils";
import Res from '../../res';
import Button from "../../components/Button";
import camelCase from "camelcase";
import GridLayout from "../../components/GridLayout";
import PropTypes from "prop-types";
import style from "../../config/style";
import kColor from "../../config/kColor";

const TYDevice = TYSdk.device;
const TYNative = TYSdk.native;

const {
  fishtank_switch: fishtank_switchCode,
  switch_led: switch_ledCode,
  level: levelCode,
  light_edit_bright: light_edit_brightCode,
  bright_value: bright_valueCode,
  work_mode: work_modeCode,
  light_mode_list: light_mode_listCode,
} = dpCodes;

class HomeLightView extends PureComponent {
  static propTypes = {
    dpState: PropTypes.object,
  };

  constructor(props) {
    super(props);
    const { bright_value } = this.props;
    this.state = {
      lightSet: bright_value,
    };

    const modeString =  TYSdk.device.getState("light_mode_list");
    const modeArray = modeString.split(",");
    if ( modeArray.length < 3 ) {
      const defMode = "0,1,2";
      TYDevice.putDeviceData({
        light_mode_list: defMode,
      });
    }


  }


  lightSwitchClicked = debounce(v => {
    console.log('灯光开关', v);
    const { switch_led } = this.props;
    console.log(switch_led);
    TYDevice.putDeviceData({
      [switch_ledCode]: v,
    });
  });

  modeClicked = (v => {
    console.log('模式', v);
    TYDevice.putDeviceData({
      [work_modeCode]: v,
    });
  });

  speedPopupClicked = debounce(v => {
    console.log('流光速度', v);
    Popup.list({
      type: 'radio',
      titleTextStyle: { fontSize: 16, fontWeight: 'bold' },
      styles: { title: { fontSize: 16, fontWeight: 'bold' } },
      // cancelTextStyle: { width: 100, height: 40, borderRadius: 20, textAlign: 'center', backgroundColor: '#afd8ea' },
      confirmTextStyle: { fontSize: 16, fontWeight: 'bold', color: '#22a8dc' },
      iconTintColor: '#22a8dc',
      maxItemNum: 7,
      dataSource: [
        {
          key: '1',
          title: Strings.light_speed_level_low,//'低速',
          value: 'level_1',
        },
        {
          key: '2',
          title: Strings.light_speed_level_medium,//'中速',
          value: 'level_2',
        },
        {
          key: '3',
          title: Strings.light_speed_level_high,//'高速',
          value: 'level_3',
        },
      ],
      title: Strings.light_speed_level_title,//'流光速度',
      cancelText: Strings.cancel,//'取消',
      confirmText: Strings.ok,//'确认',
      value: v,
      // footerType: 'singleCancel',
      onMaskPress: ({ close }) => close(),
      onSelect: (value, { close }) => {
        // setState({ listValue: value });
      },
      onConfirm: (value, { close }) => {
        TYDevice.putDeviceData({
          [levelCode]: value,
        });
        close();
      },
    });
  });

  sliderClicked = debounce(v => {
    console.log('灯光亮度', v);
    TYDevice.putDeviceData({
      [bright_valueCode]: v,
    });
  });

  lightTimerClicked = debounce(() => {
    console.log('灯光定时');
    TYSdk.Navigator.push({
      id: 'lightTimer',
    });
  });

  moreClicked = debounce(() => {
    console.log('更多');
    TYSdk.Navigator.push({
      id: 'lightMode',
    });
  });

  getData() {
    const { switch_led, work_mode } = this.props;
    const mode1 = {
      key: 'Color1',
      title: '南美风',
      icon: Res.fmode1,
      selected: work_mode === 'Color1',
      onPress: () => {this.modeClicked('Color1');},
    };
    const mode2 = {
      key: 'Color2',
      title: '溪流风',
      icon: Res.fmode2,
      selected: work_mode === 'Color2',
      onPress: () => {this.modeClicked('Color2');},
    };
    const mode3 = {
      key: 'Color3',
      title: '白光',
      icon: Res.fmode3,
      selected: work_mode === 'Color3',
      onPress: () => {this.modeClicked('Color3');},
    };
    const mode4 = {
      key: 'Night',
      title: '夜灯模式',
      icon: Res.fmode4,
      selected: work_mode === 'Night',
      onPress: () => {this.modeClicked('Night');},
    };
    const mode5 = {
      key: 'Day',
      title: '日光',
      icon: Res.fmode5,
      selected: work_mode === 'Day',
      onPress: () => {this.modeClicked('Day');},
    };
    const mode6 = {
      key: 'Flow',
      title: '流光',
      icon: Res.fmode6,
      selected: work_mode === 'Flow',
      onPress: () => {this.modeClicked('Flow');},
    };
    const mode7 = {
      key: 'Grass',
      title: '水草灯',
      icon: Res.fmode7,
      selected: work_mode === 'Grass',
      onPress: () => {this.modeClicked('Grass');},
    };
    const mode8 = {
      key: '7',
      title: ' ',
    };
    const data = [];

    data.push(mode1);
    data.push(mode2);
    data.push(mode3);
    data.push(mode4);
    data.push(mode5);
    data.push(mode6);
    data.push(mode7);
    data.push(mode8);

    return data;
  }

  // 流光速度
  flowSpeedView(disabled) {
    const { level } = this.props;
    let levelStr = '';
    if (level === 'level_1') {
      levelStr = Strings.light_speed_level_low;//'低速';
    } else if (level === 'level_2') {
      levelStr = Strings.light_speed_level_medium;//'中速';
    } else if (level === 'level_3') {
      levelStr = Strings.light_speed_level_high;//'高速';
    }

    return (
      <View style={{flex: 1}}>
          <TouchableOpacity style={styles.row} disabled={disabled} onPress={() => {this.speedPopupClicked(level);}}>
            <View style={[styles.rowBgView]}>
              <ImageBackground style={styles.icon} resizeMode="center" source={Res.fspeed} />
              <Text style={[styles.rowTitle, kColor.theme[kColor.type].titleColor]}>{Strings.light_speed_level_title}</Text>
            </View>
            <View style={{flexDirection: 'row', alignItems: 'center',}}>
              <Text style={[ kColor.theme[kColor.type].rightTitleColor, { marginRight: 0, fontSize: 13, fontWeight: '400' }]}>{levelStr}</Text>
              <Image style={[styles.arrow]} source={Res.enter} />
            </View>
          </TouchableOpacity>

          { this.lineView() }

      </View>

    );
  }

  // 灯光亮度
  lightBrightView(disabled) {
    const { bright_value } = this.props;

    return (
      // <View>
        <View style={styles.lightview}>
          <View style={styles.rowBgView}>
            <Text style={[styles.topText,kColor.theme[kColor.type].titleColor]}>{Strings.light_brightness_title}</Text>
            <View style={{ height: 14, width: 0.5, marginLeft: 5, marginRight: 5, backgroundColor: '#939494'}}></View>
            <Text style={[kColor.theme[kColor.type].subTitleColor, { fontSize: 13, fontWeight: '400'}]}>{bright_value}%</Text>
          </View>
          <Slider.Horizontal
            disabled={disabled}
            // canTouchTrack={true}
            maximumValue={100}
            minimumValue={1}
            stepValue={1}
            value={bright_value}
            type="parcel"
            style={{ marginTop: 10, marginBottom: 10, marginLeft: 20, marginRight: 20 }}
            theme={{
              width: 300,
              height: 48,
              trackRadius: 24,
              trackHeight: 48,
              thumbSize: 38,// 滑块大小
              thumbRadius: 19,// 滑块圆角
              thumbTintColor: '#ffffff',
              minimumTrackTintColor: '#22a8dc',
              maximumTrackTintColor: '#E5E5E5',
            }}
            trackStyle={{
              height: 48,
              borderRadius: 24,
            }}
            thumbStyle={{
              // 会覆盖上面 theme 的thumbSize和thumbRadius
              width: 38,
              height: 38,
              borderRadius: 19,
              shadowOffset: {// 去掉滑块阴影
                width: 0,
                height: 0,
              },
              shadowOpacity: 0,
              shadowRadius: 0,
              elevation: 0,
              justifyContent: 'center',
              alignItems: 'center',
            }}
            thumbTouchSize={{ width: 48, height: 48 }}// 控制使最大最小时外圈保持正圆状态
            renderMinimumTrack={() => (
              <View
                style={{
                  height: 48,
                  borderRadius: 24,
                  // backgroundColor: '#ac4545',
                }}>
                <Text style={{ marginLeft: 20, marginTop:15, color: '#fff', }}>1</Text>
              </View>
            )}
            renderMaximumTrack={() => (
              <View
                style={{
                  height: 48,
                  borderRadius: 24,
                  // backgroundColor: '#ac4545',
                }}>
                <Text style={{ alignSelf:'flex-end', marginRight: 20, marginTop:15, color: '#747474', }}>100</Text>
              </View>
            )}
            onValueChange={value => {
              this.setState({
                lightSet: value,
              });
              this.sliderClicked(value);
            }}
            onSlidingComplete={value => {
              this.setState({
                lightSet: value,
              });
              this.sliderClicked(value);
            }}
          />


        </View>

    );
  }

  // 灯光定时
  lightTimerView(disabled) {
    return (
      <View>
        { this.lineView() }
        <View style={[!disabled ? style.grayHidden : style.grayBackground]}>
          <TouchableOpacity style={styles.row} disabled={disabled} onPress={() => {
            this.lightTimerClicked();
          }}>
            <View style={styles.rowBgView}>
              <ImageBackground style={styles.icon} resizeMode="center" source={Res.ftimer} />
              <Text style={[styles.rowTitle, kColor.theme[kColor.type].titleColor]}>{Strings.light_timer_title}</Text>
            </View>
            <Image style={styles.arrow} source={Res.enter} />
          </TouchableOpacity>
        </View>
      </View>

    );
  }

  // 分割线
  lineView() {
    return (
      <Divider style={{ marginTop:0, marginBottom:0, height:1, alignSelf: 'center' }} color={kColor.type === 'dark'?"#FFFFFF1F":"#0000001F"} width={Dimensions.get('window').width-64} />
    );
  }

  render() {
    const { fishtank_switch, switch_led, work_mode, bright_value } = this.props;
    const {  } = this.state;
    let modeList = [];
    modeList = TYSdk.getHomeLightModeList();
    const modeRowNum = modeList.length > 4 ? 2 : 1;
    const modeHeight = modeRowNum === 1 ? 120 : 230;
    const enable = !!(switch_led && fishtank_switch);
    // console.log('灯光 enable', enable);
    // console.log('modeList', modeList);
    // console.log('modeRowNum', modeRowNum , 'modeHeight', modeHeight);

    // kColor.type = 'light';


    return (
      <View style={[styles.container,kColor.theme[kColor.type].homeCardBgColor]}>
        {/* 灯光  {backgroundColor: enable ? 'transparent':'rgb(244,244,244,0.3)'} */}
        <View style={[styles.topview, fishtank_switch ? style.grayHidden : style.grayBackground]}>
          <Text style={[styles.topText, kColor.theme[kColor.type].titleColor]}>{Strings.light_title}</Text>
          <SwitchButton
            disabled={!fishtank_switch}
            style={{ marginRight: 20 }}
            value={switch_led}
            onValueChange={v => {
              this.lightSwitchClicked(v);
            }}
          />
        </View>

          <View style={[enable ? style.grayHidden : style.grayBackground]}>

            {/* 模式 */}
            <View style={[styles.modeview, { height: modeHeight }]}>
              <GridLayout style={{ height: modeHeight }} rowNum={modeRowNum} data={modeList}>
                {({ disabled, selected, ...props }) => {
                  // const iconColor = disabled ? activeIconBgColor : activeFontColor;
                  // const iconBgColor = disabled ? inActiveIconBgColor : activeIconBgColor;
                  return (
                    <Button
                      {...props}
                      accessibilityLabel={`HomeLightView_${camelCase(props.key, {
                        pascalCase: true
                      })}`}
                      disabled={disabled}
                      selected={selected}
                      selectedBgColor={kColor.theme[kColor.type].homeCardBgColor}
                      selectedTitleColor={kColor.theme[kColor.type].titleColor}
                      titleColor={kColor.theme[kColor.type].rightTitleColor}
                      iconStyle={styles.gridLayoutIcon}
                      // labelStyle={styles.label}
                    />
                  );
                }}
              </GridLayout>
            </View>

            {/* 更多 */}
            <View style={styles.moreview}>
              <BrickButton
                text={Strings.light_button_title_more}
                textStyle={ [kColor.theme[kColor.type].moreTitleColor] }
                wrapperStyle={ [kColor.theme[kColor.type].btnBgLightGrayColor, { width: 320, alignContent: "center" }]}
                loadingSize="large"
                onPress={() => {
                  if (enable) {
                    this.moreClicked();
                  }
                }}
              />
            </View>

            <Divider style={{ marginTop: 20, alignSelf: "center" }} color={kColor.theme[kColor.type].lineColor}
                     width={Dimensions.get("window").width - 64} />

            {/* 流光速度 */}
            {work_mode === "Flow" ? this.flowSpeedView(!enable) : null}


            {/* 亮度 日光、水草灯不可设置亮度 */}
            {work_mode === "Day" || work_mode === "Grass" ? null : this.lightBrightView(!enable)}

          </View>

        {/* 灯光定时 */}
        { TYSdk.devInfo.isShare ? null : this.lightTimerView(!fishtank_switch) }

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1A1A1A',
    marginHorizontal: 10,
    marginTop: 10,
    marginRight: 10,
    borderRadius: 12,
    overflow: 'hidden',// 设置为hidden以裁剪子控件
  },
  topview: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: 'transparent',
    height: 50,
    width: '100%',
  },
  modeview: {
    alignSelf: 'stretch',
    width: '100%',
    marginTop: 10,
  },
  gridLayoutIcon: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 48,
    height: 48,
    borderRadius: 24,
    // color: '#22a8dc',
  },
  moreview: {
    alignItems: 'center',
    justifyContent: 'space-between',
    // backgroundColor: '#22a8dc',
    height: 50,
    width: '100%',
  },
  lightview: {
    backgroundColor: 'transparent',
    height: 118,
    width: Dimensions.get('window').width-20,
  },
  topText: {
    // marginTop: 20,
    marginStart: 20,
    // height: 30,
    fontSize: 16,
    fontWeight: '500',
    color: '#000',
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    // backgroundColor: '#ffffff',
    height: 80,
    // width: '100%',
    // marginHorizontal: 10,
    // marginTop: 10,
    marginRight: 0,
    paddingRight: 0,
    // borderRadius: 12,
  },
  rowBgView: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  rowTitle: {
    marginStart: 13,
    fontSize: 16,
    fontWeight: 'bold',
    color: '#000',
  },
  icon: {
    justifyContent: 'center',
    marginStart: 20,
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#22a8dc',
  },
  arrow: {
    marginLeft: 0,
    marginRight:0,
  },
});

export default connect(({ dpState }) => ({
  dpState,
  fishtank_switch: dpState[fishtank_switchCode],
  switch_led: dpState[switch_ledCode],
  level: dpState[levelCode],
  light_edit_bright: dpState[light_edit_brightCode],
  bright_value: dpState[bright_valueCode],
  work_mode: dpState[work_modeCode],
  light_mode_list: dpState[light_mode_listCode],
}))(HomeLightView);
